package com.fz.security.filter;

import com.fz.entity.system.User;
import com.fz.security.config.SecurityProperties;
import com.fz.security.provider.TokenProvider;
import com.fz.utils.JacksonUtils;
import com.fz.utils.RedisUtil;
import com.fz.utils.SpringContextUtil;
import com.fz.utils.StringUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author /
 */
public class TokenFilter extends GenericFilterBean {


   private static final Logger logger = LoggerFactory.getLogger(TokenFilter.class);
   private final TokenProvider tokenProvider;

   public TokenFilter(TokenProvider tokenProvider) {
      this.tokenProvider = tokenProvider;
   }

   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
      HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
      String token = resolveToken(httpServletRequest);
      String requestRri = httpServletRequest.getRequestURI();
      RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);
       //验证 token 是否存在
      User user = null;
      try {
         Object object = redisUtil.get(token);
         if(object != null){
            user = JacksonUtils.string2Obj(JacksonUtils.obj2String(object), User.class);
         }
      } catch (ExpiredJwtException e) {
         logger.error(e.getMessage());
      }
      // 当用户存在、token合法才进行授权
      if (user != null && StringUtils.isNotEmpty(token) && tokenProvider.validateToken(token)) {
         Authentication authentication = tokenProvider.getAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(authentication);
         logger.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
      } else {
         logger.debug("no valid JWT token found, uri: {}", requestRri);
      }

      filterChain.doFilter(servletRequest, servletResponse);
   }
   /**
    * @方法描述: 获取当前传输的token
    * @参数:
    * @返回值:
    * @创建人: I am God
    * @创建时间:: 2021/3/18
    */
   private String resolveToken(HttpServletRequest request) {
      SecurityProperties properties = SpringContextUtil.getBean(SecurityProperties.class);
      String bearerToken = request.getHeader(properties.getHeader());
      if (StringUtils.isNotEmpty(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
         return bearerToken.substring(7);
      }
      return null;
   }
}
